package main

import (
	"context"
	"strings"

	"github.com/topfreegames/pitaya/v2"
	"github.com/topfreegames/pitaya/v2/acceptor"
	"github.com/topfreegames/pitaya/v2/component"
	"github.com/topfreegames/pitaya/v2/config"
)

type TestComponent struct {
	component.Base
	app pitaya.Pitaya
}

type TestMessage struct {
	Message string `json:"message"`
}
type TestRespone struct {
	Code int `json:"code"`
}

func NewTestComponent(app pitaya.Pitaya) *TestComponent {
	return &TestComponent{
		app: app,
	}
}

func (c *TestComponent) One(ctx context.Context, msg []byte) ([]byte, error) {
	s := c.app.GetSessionFromCtx(ctx)

	s.Push("one", "i get one message")
	s.Push("message", []byte("your message :"+string(msg)))

	return msg, nil
}

func (c *TestComponent) Two(ctx context.Context, msg *TestMessage) (*TestRespone, error) {
	s := c.app.GetSessionFromCtx(ctx)

	s.Push("two", "i get 2 message:"+msg.Message)
	return &TestRespone{Code: 1}, nil
}

var app pitaya.Pitaya

func main() {

	// 配置
	conf := config.NewDefaultBuilderConfig()

	// 火龙果
	builder := pitaya.NewDefaultBuilder(true, "game", pitaya.Cluster, map[string]string{}, *conf)
	builder.AddAcceptor(acceptor.NewTCPAcceptor(":8999"))
	app = builder.Build()
	defer app.Shutdown()

	tc := NewTestComponent(app)
	app.Register(tc, component.WithName("testcomponent"), component.WithNameFunc(strings.ToLower))

	app.Start()

}
